const { app, BrowserWindow, Tray, Menu, ipcMain, Notification, shell } = require('electron')
const path = require('path')
const AutoLaunch = require('auto-launch')

class ElectronApp {
  constructor() {
    this.mainWindow = null
    this.tray = null
    this.autoLauncher = null
    this.unreadCount = 0
    
    this.init()
  }

  init() {
    // 设置自启动
    this.autoLauncher = new AutoLaunch({
      name: '消息推送助手',
      path: app.getPath('exe')
    })

    // 应用事件监听
    app.whenReady().then(() => {
      this.createWindow()
      this.createTray()
      this.setupIPC()
    })

    app.on('window-all-closed', () => {
      if (process.platform !== 'darwin') {
        app.quit()
      }
    })

    app.on('activate', () => {
      if (BrowserWindow.getAllWindows().length === 0) {
        this.createWindow()
      }
    })

    // 防止多实例
    const gotTheLock = app.requestSingleInstanceLock()
    if (!gotTheLock) {
      app.quit()
    } else {
      app.on('second-instance', () => {
        if (this.mainWindow) {
          if (this.mainWindow.isMinimized()) this.mainWindow.restore()
          this.mainWindow.focus()
        }
      })
    }
  }

  createWindow() {
    this.mainWindow = new BrowserWindow({
      width: 1000,
      height: 700,
      minWidth: 800,
      minHeight: 600,
      webPreferences: {
        nodeIntegration: false,
        contextIsolation: true,
        preload: path.join(__dirname, 'preload.js')
      },
      icon: this.getIconPath(),
      show: false,
      titleBarStyle: process.platform === 'darwin' ? 'hiddenInset' : 'default'
    })

    // 加载应用
    if (process.env.NODE_ENV === 'development') {
      this.mainWindow.loadURL('http://localhost:5173')
      this.mainWindow.webContents.openDevTools()
    } else {
      this.mainWindow.loadFile(path.join(__dirname, '../dist/index.html'))
    }

    // 窗口事件
    this.mainWindow.once('ready-to-show', () => {
      this.mainWindow.show()
    })

    this.mainWindow.on('close', (event) => {
      if (!app.isQuiting) {
        event.preventDefault()
        this.mainWindow.hide()
        
        if (process.platform === 'darwin') {
          app.dock.hide()
        }
      }
    })

    this.mainWindow.on('minimize', (event) => {
      if (process.platform === 'win32') {
        event.preventDefault()
        this.mainWindow.hide()
      }
    })
  }

  createTray() {
    const iconPath = this.getIconPath()
    
    // 如果没有图标文件，跳过托盘创建
    if (!iconPath) {
      console.log('图标文件不存在，跳过托盘创建')
      return
    }
    
    this.tray = new Tray(iconPath)

    const contextMenu = Menu.buildFromTemplate([
      {
        label: '打开应用',
        click: () => {
          this.showWindow()
        }
      },
      {
        label: '设置',
        click: () => {
          this.showWindow()
          this.mainWindow.webContents.send('navigate-to', '/settings')
        }
      },
      { type: 'separator' },
      {
        label: '退出',
        click: () => {
          app.isQuiting = true
          app.quit()
        }
      }
    ])

    this.tray.setContextMenu(contextMenu)
    this.tray.setToolTip('消息推送助手')

    this.tray.on('click', () => {
      this.showWindow()
    })

    this.tray.on('double-click', () => {
      this.showWindow()
    })
  }

  showWindow() {
    if (this.mainWindow) {
      if (this.mainWindow.isMinimized()) {
        this.mainWindow.restore()
      }
      this.mainWindow.show()
      this.mainWindow.focus()
      
      if (process.platform === 'darwin') {
        app.dock.show()
      }
    }
  }

  getIconPath() {
    const iconName = process.platform === 'win32' ? 'icon.ico' : 'icon.png'
    const iconPath = path.join(__dirname, 'assets', iconName)
    
    // 检查图标文件是否存在，如果不存在则返回 null
    const fs = require('fs')
    if (fs.existsSync(iconPath)) {
      return iconPath
    }
    
    // 如果图标文件不存在，返回 null，Electron 会使用默认图标
    return null
  }

  setupIPC() {
    // 显示系统通知
    ipcMain.handle('show-notification', async (event, { title, body, tag }) => {
      if (Notification.isSupported()) {
        const notification = new Notification({
          title,
          body,
          tag,
          icon: this.getIconPath()
        })

        notification.on('click', () => {
          this.showWindow()
          this.mainWindow.webContents.send('notification-clicked', tag)
        })

        notification.show()
        return true
      }
      return false
    })

    // 设置未读数角标
    ipcMain.handle('set-badge-count', async (event, count) => {
      this.unreadCount = count
      
      if (process.platform === 'darwin') {
        app.dock.setBadge(count > 0 ? count.toString() : '')
      } else if (process.platform === 'win32') {
        // Windows 在托盘图标上显示未读数
        if (this.tray) {
          const tooltip = count > 0 ? `消息推送助手 (${count} 条未读)` : '消息推送助手'
          this.tray.setToolTip(tooltip)
        }
      }
      
      return true
    })

    // 设置开机自启
    ipcMain.handle('set-auto-launch', async (event, enabled) => {
      try {
        if (enabled) {
          await this.autoLauncher.enable()
        } else {
          await this.autoLauncher.disable()
        }
        return true
      } catch (error) {
        console.error('设置开机自启失败:', error)
        return false
      }
    })

    // 获取开机自启状态
    ipcMain.handle('get-auto-launch', async () => {
      try {
        return await this.autoLauncher.isEnabled()
      } catch (error) {
        console.error('获取开机自启状态失败:', error)
        return false
      }
    })

    // 最小化到托盘
    ipcMain.handle('minimize-to-tray', async () => {
      if (this.mainWindow) {
        this.mainWindow.hide()
        if (process.platform === 'darwin') {
          app.dock.hide()
        }
      }
      return true
    })

    // 退出应用
    ipcMain.handle('quit-app', async () => {
      app.isQuiting = true
      app.quit()
      return true
    })
  }
}

new ElectronApp()